<template>
  <ContainerGroup>
    <Container style="margin-bottom: 10px">
      <FilterForm
        ref="filterForm"
        :elements="elements"
        @submit="handleSearch"
        :noimmediate="true"
        @reset="handleReset"
      >
        <Button v-if="!imageShow" icon="add" type="plain" @click="handleAdd">新增</Button>
        <Button v-if="!imageShow" type="plain" @click="handleInherit"
          >继承</Button
        >
      </FilterForm>
    </Container>
    <Container height="fill" style="position: relative;">
      <div class="wraper">
        <div v-if="imageShow" class="image-srcc">
          <img src="../../../assets/image/archived.png" alt="" />
        </div>
        <Table
          :columns="CmpColumns"
          :loading="tableLoading"
          :data="tableData"
          :pagination="{
            total: total,
            current: currentPage,
            pageSize: pageSize,
          }"
          @paginationChange="pageChange"
          :span-method="personObjectSpanMethod"
        >
          <template #caozuo="{ row }">
            <Tooltip content="编辑" icon="edit" @click="handleEdit(row)" />
            <Tooltip content="删除" icon="delete" @click="handleDelete(row)" />
            <!-- {{ row.caozuo }} -->
          </template>
        </Table>
      </div>
      <!-- 新增、编辑 -->
      <Drawer
        ref="drawerRef"
        :title="title"
        :visible.sync="showDrawer"
        width="1270px"
        :footer-btns="[
          {
            text: '确认',
            type: 'primary',
            loading: qrLoading,
            trigger: 'submit',
          },
          {
            text: '取消',
            type: 'info',
            trigger: 'cancel',
          },
        ]"
        @submit="handleSubmit"
        @cancel="showDrawer = false"
      >
        <NewInfo ref="newinfoRef" v-if="showDrawer" :current="currentRow" />
      </Drawer>
      <!-- 继承 -->
      <el-dialog
        title="继承"
        :visible.sync="centerDialogVisible"
        top="30vh"
        width="30%"
      >
        <div class="dialog-inherit">
          <span>继承周期：</span>
          <el-select v-model="inheritCycle" placeholder="请选择">
            <el-option
              v-for="item in elements[0].options"
              :key="item.periodSuffix"
              :label="item.periodPull"
              :value="item.periodSuffix"
            />
          </el-select>
        </div>
        <!-- <div class="dialog-inherit">
          <span>目标周期：</span>
          <el-select v-model="targetCycle" placeholder="请选择">
            <el-option
              v-for="item in elements[0].options"
              :key="item.id"
              :label="item.periodPull"
              :value="item.id"
            />
          </el-select>
        </div> -->
        <div class="dialog-but">
          <el-button @click="handleClaer">取消</el-button>
          <el-button type="primary" :loading="btnLoading" @click="handleConfim"
            >确认</el-button
          >
        </div>
      </el-dialog>
    </Container>
  </ContainerGroup>
</template>
<script>
import NewInfo from "./newInfo.vue";
import {
  listByPageAdministration,
  getAssessmentCyclePull,
  insertWorkloadTargetAdministration,
  updateWorkloadTargetAdministration,
  deleteWorkloadAdministration,
  inherit,
  getAssessmentCycleById,
} from "@/api/targetManagement";
export default {
  components: {
    NewInfo,
  },
  data() {
    return {
      centerDialogVisible: false,
      kxList: [],
      qrLoading: false,
      btnType: 1,
      optionList: [],
      darawerLoading: false,
      showDrawer: false,
      title: "",
      fileList: [],
      importLoading: false,
      tableColumns: [
        {
          title: "工作量指标编码",
          dataIndex: "workloadCode",
        },
        {
          title: "工作量指标名称",
          dataIndex: "workloadName",
        },
        // {
        //   title: "科室编码",
        //   dataIndex: "deptCodeInfo",
        // },
        {
          title: "核算单元",
          dataIndex: "deptNameInfo",
        },
        {
          title: "开单科室",
          dataIndex: "billDeptNameInfo",
        },
        {
          title: "执行科室",
          dataIndex: "exeDeptNameInfo",
        },
        {
          title: "统计项目编码",
          dataIndex: "projectCode",
        },
        {
          title: "统计项目名称",
          dataIndex: "projectName",
        },
        {
          title: "点数",
          dataIndex: "count",
        },
        {
          title: "单位",
          dataIndex: "unitName",
        }
      ],
      total: 0,
      pageSize: 100,
      currentPage: 1,
      tableLoading: false,
      tableData: [],
      newCondition: {},
      elements: [
        {
          key: "period",
          label: "周期",
          type: "select",
          itemLabel: "periodPull",
          itemValue: "periodSuffix",
          hideSelectAll: true,
          options: [],
          value: "",
        },
        {
          label: "综合搜索",
          type: "input",
          key: "codeOrName",
          value: "",
          placeholder: "请输入工作量指标管理编码/工作量指标管理名称",
          width: 320,
        },
      ],
      currentRow: null,
      inheritCycle: "",
      targetCycle: "",
      imageShow: false,
      btnLoading: false,
    };
  },
  computed: {
    CmpColumns() {
      return this.imageShow
        ? this.tableColumns
        : [
            ...this.tableColumns,
            {
              title: "操作",
              dataIndex: "caozuo",
              type: "otherTag",
              width: 160,
            },
          ];
    },
  },
  created() {
    this.getSelect();
  },
  methods: {
    getFileInfo() {
      const id = this.elements[0].options.find(item =>item.periodSuffix===this.newCondition?.period)?.id
      getAssessmentCycleById({
        id: id,
      }).then((res) => {
        if (res.code === 0) {
          const {isFile } = res.data
          if(isFile===1){
            this.imageShow = true;
          }else {
            this.imageShow = false;
          }
        } 
      });
    },
    personObjectSpanMethod({ row, column, rowIndex, columnIndex }) {
      const self = this;
      if (columnIndex === 0) {
        return this.setMerge(self.rowAndColumn, rowIndex);
      }
      if (columnIndex === 1) {
        return this.setMerge(self.rowRoomColumn, rowIndex);
      }
      if (columnIndex === 2) {
        return this.setMerge(self.rowThree, rowIndex);
      }
      if (columnIndex === 3) {
        return this.setMerge(self.rowFour, rowIndex);
      }
      if (columnIndex === 4) {
        return this.setMerge(self.rowFour, rowIndex);
      }
      if (columnIndex === 9) {
        return this.setMerge(self.rowCaozuo, rowIndex);
      }
    },
    setMerge(arr, rowIndex) {
      if (arr[rowIndex]) {
        const rowNum = arr[rowIndex];
        return {
          rowspan: rowNum,
          colspan: rowNum > 0 ? 1 : 0,
        };
      }
      return {
        rowspan: 0,
        colspan: 0,
      };
    },
    getListDataForRowAndColumn(data) {
      let self = this;
      self.rowAndColumn = [];
      self.rowRoomColumn = [];
      self.rowThree = [];
      self.rowFour = [];
      self.rowCaozuo = [];
      for (var i = 0; i < data.length; i++) {
        if (i === 0) {
          self.rowAndColumn.push(1);
          self.pos = 0;

          self.rowRoomColumn.push(1);
          self.posT = 0;

          self.rowThree.push(1);
          self.posD = 0;

          self.rowFour.push(1);
          self.posE = 0;

          self.rowCaozuo.push(1);
          self.posC = 0;
        } else {
          if (data[i].id === data[i - 1].id) {
            self.rowAndColumn[self.pos] += 1;
            self.rowAndColumn.push(0);
            if (data[i].workloadName === data[i - 1].workloadName) {
              self.rowRoomColumn[self.posT] += 1;
              self.rowRoomColumn.push(0);
            }
            if (data[i].deptCodeInfo === data[i - 1].deptCodeInfo) {
              self.rowThree[self.posD] += 1;
              self.rowThree.push(0);
            }
            if (data[i].deptNameInfo === data[i - 1].deptNameInfo) {
              self.rowFour[self.posE] += 1;
              self.rowFour.push(0);
            }
            if (data[i].caozuo === data[i - 1].caozuo) {
              self.rowCaozuo[self.posC] += 1;
              self.rowCaozuo.push(0);
            }
            // else {
            //   self.rowRoomColumn.push(1);
            //   self.posT = i;
            // }
          } else {
            self.rowAndColumn.push(1);
            self.pos = i;

            self.rowRoomColumn.push(1);
            self.posT = i;

            self.rowThree.push(1);
            self.posD = i;

            self.rowFour.push(1);
            self.posE = i;

            self.rowCaozuo.push(1);
            self.posC = i;
          }
        }
      }
      return data;
    },
    handleDelete(row) {
      // 删除
      this.$ckConfirm({
        content: "此操作将删除该条记录，并无法恢复， 是否继续?",
        title: "提示",
        okFn: (res) => {
          deleteWorkloadAdministration({
            id: row.id,
            period: this.$refs.filterForm.getParms()?.period,
          }).then((res) => {
            if (res.code === 200) {
              this.currentPage = 1;
              this.getData();
              this.$message.success(res.msg);
            } else {
              this.$message.error(res.msg);
            }
          });
        },
        cancelFn: (res) => {
          console.log("取消");
        },
      });
    },
    handleAdd() {
      this.currentRow = null;
      this.btnType = 1;
      this.title = "添加工作量指标";
      this.showDrawer = true;
    },
    getSelect() {
      // 周期
      getAssessmentCyclePull().then((res) => {
        if (res.code === 200) {
          this.elements[0].options = res.data;
          const { periodSuffix } = res.data[0];
          this.elements[0].value = periodSuffix;
          localStorage.setItem(
            "cycle",
            JSON.stringify(this.elements[0].options)
          );
          setTimeout(() => {
            this.handleSearch(this.$refs.filterForm.getParms())
          }, 1000)
        } else {
          this.$message.error(res.msg);
        }
      });
    },
    handleSubmit() {
      const { flag, formData } = this.$refs.newinfoRef.getFormData();
      if (flag) {
        const param = formData;
        param.period = this.$refs.filterForm.getParms()?.period;
        param.id = (this.currentRow && this.currentRow.id) || undefined;
        this.qrLoading = true;
        const api = !this.currentRow
          ? insertWorkloadTargetAdministration
          : updateWorkloadTargetAdministration;
        api(param).then((res) => {
          this.qrLoading = false;
          if (res.code === 200) {
            this.getData();
            this.showDrawer = false;
            this.$message.success(res.msg);
          } else {
            this.$message.error(res.msg);
          }
        });
      }
    },
    // 查询
    handleSearch(value) {
      this.newCondition = value;
      this.currentPage = 1;
      this.getData();
      this.getFileInfo();
    },
    // 重置
    handleReset(val) {
      this.handleSearch(val);
    },
    handleEdit(row) {
      // 编辑
      this.currentRow = row;
      this.$set(
        this.currentRow,
        "period",
        this.$refs.filterForm.getParms()?.period
      );
      this.btnType = 2;
      this.title = "编辑工作量指标";
      this.handleSetForm(row);
      this.showDrawer = true;
    },
    handleSetForm(row) {
      this.$handleSetForm(this.drawerForm, 1, row);
    },
    // 继承
    handleInherit() {
      this.centerDialogVisible = true;
    },
    handleClaer() {
      this.inheritCycle = "";
      // this.targetCycle = "";
      this.centerDialogVisible = false;
    },
    handleConfim() {
      if (this.inheritCycle === this.$refs.filterForm.getParms()?.period) {
        this.$message.warning("不能继承自己的数据");
        return;
      }
      const param = {
        beInheritedPeriod: this.inheritCycle,
        inheritPeriod: this.$refs.filterForm.getParms()?.period,
      };
      this.btnLoading = true;
      inherit(param)
        .then((res) => {
          this.btnLoading = false;
          if (res.code === 200) {
            this.$message.success(res.msg);
            this.handleClaer();
          } else {
            this.$message.error(res.msg);
          }
        })
        .catch(() => {
          this.btnLoading = false;
        });
    },
    getData() {
      const params = {
        pageNum: this.currentPage,
        pageSize: this.pageSize,
        period: this.newCondition.period,
        codeOrName: this.newCondition.codeOrName,
      };
      this.tableLoading = true;
      listByPageAdministration(params)
        .then((res) => {
          this.tableLoading = false;
          if (res.code === 200) {
            const arr = res.data.records.map((item) => {
              item.caozuo = item.id;
              return item;
            });
            this.tableData = this.getListDataForRowAndColumn(arr);
            this.total = res.data.total;
          } else {
            this.$message.error(res.msg);
          }
        })
        .catch(() => {
          this.tableLoading = false;
        });
    },
    pageChange(payload) {
      this.currentPage = payload.current;
      this.pageSize = payload.pageSize;
      this.getData();
    },
  },
};
</script>
<style lang="less" scoped>
.wraper {
  display: flex;
  height: 100%;
  overflow: hidden;
  // position: relative;
  .upload-demo {
    .buttons {
      margin: 0px 5px;
      height: 27px;
      margin-top: -1px;
    }
  }
}
/deep/.el-dialog__header {
  padding: 10px 10px 0px 10px;
  padding-bottom: 0px;
}
/deep/.el-dialog__title {
  font-size: 15px;
}
/deep/.el-dialog__headerbtn {
  top: 10px;
}
/deep/.el-dialog__body {
  padding: 10px;
}
.dialog-inherit {
  display: flex;
  flex-direction: row;
  margin: 10px;
  justify-content: center;
  span {
    margin-top: 5px;
  }
}
.dialog-but {
  margin: 10px;
  display: flex;
  flex-direction: row;
  justify-content: right;
}
.image-srcc {
  width: 60px;
  height: 60px;
  position: absolute;
  top: 5px;
  left: 130px;
  z-index: 2;
  img {
    width: 100%;
    height: 100%;
  }
}
</style>
